import com from "./com";
import config from "./config";
import api from "./api";
export default {
    selectedPath:[],//选择出来的照片原地址
    preparedPath:[],//经过处理过后的临时数组
    uploadedPath:[],//上传后拿到的服务器地址
    quality:0.3,
    maxWidth:2000,
    numTotal:0,
    numUpload:0,
    uploading:false,
    cbFunc:function(){},
    initialize:function(){

    }
    ,select:function (maxNum) {
        if(maxNum === undefined) maxNum = 9;
        var _this = this
        uni.chooseImage({
            count: maxNum, //默认9
            sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album'], //从相册选择
            success: function (res) {
                console.log(JSON.stringify(res.tempFilePaths));
                // logJson(ret,"PIC_1:")
                if (res.tempFilePaths !== undefined) {
                    var totalPic = res.tempFilePaths.length;
                    if (totalPic === 0){
                        com.showToast('请选择图片')
                        return false
                    }
                    res.tempFilePaths.map(function (data) {
                        _this.selectedPath.push(data)
                    })
                    _this.autoUpload();
                }
            }
        });
        // UIAlbumBrowser.open({
        //     max: maxNum,
        //     image: 'image',
        //     styles: {
        //         bg: '#fff',
        //         mark: {
        //             icon: '',
        //             position: 'top_right',
        //             size: 30
        //         },
        //         nav: {
        //             bg: 'rgba(0,0,0,0.6)',
        //             titleColor: '#fff',
        //             titleSize: 18,
        //             cancelColor: '#fff',
        //             cancelSize: 16,
        //             finishColor: '#fff',
        //             finishSize: 16
        //         }
        //     },
        //     rotation: false
        // }, function(ret) {
        //     logJson(ret,"PIC_1:")
        //     if (ret.list !== undefined) {
        //         var totalPic = ret.list.length;
        //         if (totalPic === 0){
        //             showToast('请选择图片')
        //             return false
        //         }
        //         ret.list.map(function (data) {
        //             _this.selectedPath.push(data.path)
        //         })
        //         _this.autoUpload();
        //     }
        // });
        return this;
    }
    ,selectEdit:function (func) {
        // UIAlbumBrowser.open({
        //     max: 1,
        //     image: 'image',
        //     styles: {
        //         bg: '#fff',
        //         mark: {
        //             icon: '',
        //             position: 'top_right',
        //             size: 30
        //         },
        //         nav: {
        //             bg: 'rgba(0,0,0,0.6)',
        //             titleColor: '#fff',
        //             titleSize: 18,
        //             cancelColor: '#fff',
        //             cancelSize: 16,
        //             finishColor: '#fff',
        //             finishSize: 16
        //         }
        //     },
        //     rotation: false
        // }, function(ret) {
        //     if (ret.list !== undefined) {
        //         var totalPic = ret.list.length;
        //         if (totalPic === 0){
        //             showToast('请选择图片')
        //             return false
        //         }
        //         var path = ret.list[0].path
        //         FNImageClip.open({
        //             rect: {
        //                 x: 0,
        //                 y: 0,
        //                 w: api.winWidth,
        //                 h: api.winHeight - api.winWidth/10
        //             },
        //             srcPath: path,
        //             style: {
        //                 mask: 'rgba(0,0,0,0.5)',
        //                 clip: {
        //                     w: api.winWidth/2,
        //                     h: api.winWidth/2,
        //                     x: api.winWidth/4,
        //                     y: (api.winHeight - api.winWidth/10 - api.winWidth/2)/2,
        //                     borderColor: '#FFF',
        //                     borderWidth: 2,
        //                     appearance: 'rectangle'
        //                 }
        //             },
        //             fixedOn: api.frameName,
        //             mode:'image'
        //         }, function(ret, err) {
        //             if (ret) {
        //                 func()
        //                 // alert(JSON.stringify(ret));
        //             } else {
        //                 alert(JSON.stringify(err));
        //             }
        //         });
        //     }
        // });
        // return this;
    }
    ,upload:function (picPath) {
        var _this = this;
        // _this.uploadedPath = []

        if (config.assetType === 2) {
            // showToast("正在上传")
            // uploadOnePicToOss(picPath,function (path) {
            //     _this.uploadedPath.push(path)
            //     _this.cbFunc(_this.uploadedPath)
            //     _this.numUpload ++
            //
            //     if (_this.numUpload === _this.numTotal) {
            //         _this.uploading = false
            //     }else {
            //         _this.uploading = true
            //     }
            // });
        }else {
            api.upload( "/MyWebPicUpload" , picPath ,function (res) {
                _this.uploadedPath.push(res.d)
                _this.cbFunc(_this.uploadedPath)
                _this.numUpload ++
                if (_this.numUpload === _this.numTotal) {
                    _this.uploading = false
                }else {
                    _this.uploading = true
                }
            })
        }
    }
    ,compress:function (picPath) {
        var _this = this
// #ifdef  H5
        _this.upload(picPath)
// #endif
// #ifndef  H5
        uni.compressImage({
            src: picPath,
            quality: 80,
            success: res => {
                console.log(res.tempFilePath)
                _this.upload(res.tempFilePath)
            }
        })
// #endif
    }
    ,autoUpload:function () {
        var _this = this
        var selectedPicNum = _this.selectedPath.length
        _this.numTotal = selectedPicNum;
        _this.numUpload = 0;
        var int = setInterval(function () {
            selectedPicNum = _this.selectedPath.length;
            // showToast(selectedPicNum + "个文件待上传")
            //检查并压缩图片压缩后上传，延迟根据服务器能力修改
            if (selectedPicNum > 0) {
                _this.compress(_this.selectedPath.shift())
            }else {
                clearInterval(int)
            }
            // this.selectedPath.shift()
        },100)
    }
    ,setCbFunc:function (cbFunc) {
        this.cbFunc = cbFunc
    }
    ,removePic:function (picIndex,pics){
        var update = false;
        if (pics === undefined){
            pics = this.uploadedPath
            update= true
        }
        var newData = []
        // var newViewData = []
        pics.map(function (data,index) {
            console.log(index);
            console.log(picIndex);
            if (picIndex === index) {return;}
            newData.push(data)
            // newViewData.push(baseUrl + data)
        })
        if (update) {
            this.uploadedPath = newData
        }
        return newData
    }
    ,setData:function (data) {
        this.uploadedPath = data
        return this;
    }
    ,getData:function () {
        return this.uploadedPath;
    }
    ,getViewData:function (pics) {
        if (pics === undefined){
            pics = this.uploadedPath
        }
        var newData = []
        pics.map(function (data) {
            // newData.push(getAssetBaseUrl() + data)
            if (config.assetType === 2) {
                newData.push(api.getAssetBaseUrl() + data);
            }else {
                newData.push(api.getBaseUrl() + data);
            }
        })
        return newData
    }
    ,picMove(index,num,pics){
        var update = false;
        if (pics === undefined){
            pics = this.uploadedPath
            update= true
        }
        var curPic =  pics[index];
        var targetPic;
        var targetIndex;
        targetIndex = index + num;
        if (targetIndex >= pics.length -1) {targetIndex = pics.length -1}
        if (targetIndex <= 0) {targetIndex = 0}
        targetPic = pics[targetIndex];
        pics[index] = targetPic;
        pics[targetIndex] = curPic;
        if (update) {
            this.uploadedPath = pics
        }
        return pics;
    }
    ,editSave:function () {
        var _this = this
        FNImageClip.save({
            destPath: 'fs://imageClip/cur.png',
            copyToAlbum: false,
            quality: 1
        }, function(ret, err) {
            if (ret) {
                _this.upload(ret.destPath)
                FNImageClip.close();
            } else {
                alert(JSON.stringify(err));
            }
        });
    }
    ,editClose:function () {
        FNImageClip.close();
    }
    ,editReset:function () {
        FNImageClip.reset();
    }

    ,addPic:function (localPath) {
        this.selectedPath.push(localPath);
    }
    //选择拍照还是相册20200311新增
    ,chooseSrc:function (maxNum) {
        // var _this = this
        // api.actionSheet({
        //     title: '上传图片',
        //     cancelTitle: '取消',
        //     buttons: ['拍照','从手机相册选择']
        // }, function(ret, err) {
        //     if (ret) {
        //         // _this.getPicture(ret.buttonIndex);
        //         if (ret.buttonIndex == 1) {
        //             api.getPicture({
        //                 sourceType: 'camera',  //拍照
        //                 encodingType: 'png',
        //                 mediaValue: 'pic',
        //                 allowEdit: false,
        //                 //destinationType: 'base64',  //返回base64地址
        //                 quality: 60,
        //                 saveToPhotoAlbum: true
        //             }, function(ret, err) {
        //                 //var imgSrc = ret.base64Data;  如果是base64，要用这个属性获取地址
        //                 // 获取拍照数据并处理
        //                 if (isTrue(ret.data)) {
        //                     logJson(ret,"ret")
        //                     _this.addPic(ret.data);
        //                     _this.autoUpload();
        //                 }
        //             });
        //         }
        //         if (ret.buttonIndex == 2) {
        //             _this.select(maxNum)
        //         }
        //     }
        // });
        // return this;
    }
    //暂未使用
}

function get_suffix(filename) {
    let pos = filename.lastIndexOf('.')
    let suffix = ''
    if (pos != -1) {
        suffix = filename.substring(pos)
    }
    return suffix;
}

/* 多图页面html
 <div class="fs10 padl5 padr5 flr">
    <mu-form-item label="图集" :rules="[rules.notNull]" prop="pic">
        <div class="ofh">
            <div class="flex-r flex-nowrap">
                <mu-paper class="picCommonSize pos-r mar3" :z-depth="1"  v-for="tile, index in pics">
                    <img class="picCommonSize" :src="tile">
                    <div class="pos-a w100 r0 l0 b-3 flrc op6">
                        <mu-button fab small color="black" @click="move(index,-1)">
                            <mu-icon  value="arrow_back"></mu-icon>
                        </mu-button>
                        <mu-button fab small color="black" @click="move(index,1)">
                            <mu-icon  value="arrow_forward"></mu-icon>
                        </mu-button>
                        <mu-button fab small color="black" @click="del(index)">
                            <mu-icon  value="close"></mu-icon>
                        </mu-button>
                    </div>
                </mu-paper>
            </div>

            <div class="">
                <mu-button color="success" @click="selectPic()">选择图片</mu-button>
            </div>
        </div>
    </mu-form-item>
</div>

多图页面js
var PicUpUserHead = new PicUp()
selectPic:function () {
    var _this = this;
    PicUpUserHead.select(9).setCbFunc(function (pics) {
        _this.pics = PicUpUserHead.getViewData(pics)
    })
},
del:function (index) {
    var pics = PicUpUserHead.removePic(index)
    this.pics = PicUpUserHead.getViewData(pics)
},
move:function (index,num) {
    var pics = PicUpUserHead.picMove(index,num)
    this.pics = PicUpUserHead.getViewData(pics)
},
*/


/*头像
网页代码
<div class="fs10 padl5 padr5 flrc padt10">
    <mu-form-item label="" :rules="[rules.notNull]" prop="pic">
        <div class="">
            <div class="flrc flex1 padl5">
                <mu-paper class="ofh wh30-30 marr10" :z-depth="1">
                    <img class="wh30-30" :src="form.pic" v-if="form.pic">
                </mu-paper>
                <mu-paper :circle="true" class="ofh wh30-30" :z-depth="1">
                    <img class="wh30-30" :src="form.pic" v-if="form.pic">
                </mu-paper>
            </div>

            <div class="mart5">
                <mu-button color="success" @click="selectEditPic()" full-width>
                    选择头像
                </mu-button>
            </div>
        </div>
    </mu-form-item>
    <div class="pos-f b0 l0 w100 bc11 c13 flrc fs10" style="height: 11vw" v-if="toolsShow">
        <div class="flex1 tac"><mu-button @click="save()">保存</mu-button></div>
        <div class="flex1 tac"><mu-button @click="reset()">重置</mu-button></div>
        <div class="flex1 tac"><mu-button @click="close()">取消</mu-button></div>
    </div>
</div>

js代码
selectEditPic:function () {
    var _this = this;
    PicUpUserHead.selectEdit(()=>{_this.toolsShow = true})
        .setCbFunc(function (pics) {
        _this.form.pic = pics[0]
        _this.form.picV = PicUpUserHead.getViewData(pics)[0]
    })
}
,save:function () {
    PicUpUserHead.editSave()
    this.toolsShow = false
}
,reset:PicUpUserHead.editReset
,close:function () {
    PicUpUserHead.editClose()
    this.toolsShow = false
}
* **/

